/*
 * Copyright 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sychip.fhc.app.drawer.screen.addedittask

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.base.EventType
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.infinum.snacky.SnackyAnimationSpec
import com.infinum.snacky.SnackyHost
import com.infinum.snacky.default.ShowQuestionSnackbar
import com.infinum.snacky.rememberSnackyHostState
import com.mikepenz.iconics.compose.Image
import com.mikepenz.iconics.typeface.library.fontawesome.FontAwesome
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.EventDataTest
import com.sychip.fhc.app.wsn.common.EventDataTest2
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber


@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun AddEditTaskScreen(
    topBarTitle: String,
    onTaskUpdate: () -> Unit,
    onBack: () -> Unit,
    modifier: Modifier = Modifier,
    viewModel: AddEditTaskViewModel = hiltViewModel()
) {
    val snackbarHostState = rememberSnackyHostState()
    Scaffold(
        modifier = modifier.fillMaxSize(),
        snackbarHost = {
            SnackyHost(
                hostState = snackbarHostState,
                animationSpec = SnackyAnimationSpec(scaleFactor = 0.5f),
            )
        },
        topBar = {
            FhcTopAppBar(
                title =  topBarTitle,
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(id = R.string.menu_back))
                    }
                },
                actions = {
                    IconButton(onClick = {
                        Timber.i("TasksTopAppBar IconButton   >>>>>>onBack")
                        CoroutineScope(Dispatchers.Default).launch {

                            var a = EventDataTest()
                            var b = EventDataTest2()
                            var _a = FlowEventBusData(EventType.MockTest, a)
                            var _b = FlowEventBusData(EventType.MockTest, b)
                            a.lastName = "lastName    1111"
                            a.firstName = "firstName    2222"
                            b.aaa = "aaa >>>  1111"
                            b.bbb = "bbbb >>>  22222"
                            FhcFlowEventBus.publish(_a)
                            FhcFlowEventBus.publish(_b)

                            a = EventDataTest()
                            b = EventDataTest2()
                            _a = FlowEventBusData(EventType.MockTest, a)
                            _b = FlowEventBusData(EventType.MockTest, b)
                            a.lastName = "lastName    XXXXX"
                            a.firstName = "firstName   YYYY"
                            b.aaa = "aaa >>>  ZZZZZZZZ"
                            b.bbb = "bbb >>>  WWWWWWW"
                            FhcFlowEventBus.publish(_a)
                            FhcFlowEventBus.publish(_b)
                        }
                    }) {
                        Icon(Icons.Filled.Add, null)
                    }
                },
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = viewModel::saveTask) {
                Icon(Icons.Filled.Done, stringResource(id = R.string.cd_save_task))
            }
        }
    ) { innerPadding ->
        val uiState by viewModel.uiState.collectAsStateWithLifecycle()
        val modifier = Modifier
            .fillMaxSize()
            .padding(top = innerPadding.calculateTopPadding())
            // Consume this insets so that it's not applied again when using safeDrawing in the hierarchy below
            .consumeWindowInsets(innerPadding)
        Column( modifier) {
            AddEditTaskContent(
                loading = uiState.isLoading,
                title = uiState.title,
                description = uiState.description,
                onTitleChanged = viewModel::updateTitle,
                onDescriptionChanged = viewModel::updateDescription
            )
        }
        // Check if the task is saved and call onTaskUpdate event
        LaunchedEffect(uiState.isTaskSaved) {
            if (uiState.isTaskSaved) {
                onTaskUpdate()
            }
        }

        // Check for user messages to display on the screen
        uiState.userMessage?.let { userMessage ->
//            val snackbarText = stringResource(userMessage)
//            ShowQuestionSnackbar(
//                show = true,
//                message = snackbarText,
//                question = "How to do it???",
//                snackbarHostState = snackbarHostState,
//                questionAction = {
//                    Timber.i("   questionAction")
//                    viewModel.snackbarMessageShown()
//                },
//                okAction = {
//                    Timber.i("   okAction")
//                    viewModel.snackbarMessageShown()
//                },
//                onDismiss = {
//                    Timber.i("   onDismiss")
//                    viewModel.snackbarMessageShown()
//                }
//            )
        }
    }
}

@OptIn(ExperimentalMaterialApi::class, ExperimentalMaterialApi::class)
@Composable
private fun AddEditTaskContent(
    loading: Boolean,
    title: String,
    description: String,
    onTitleChanged: (String) -> Unit,
    onDescriptionChanged: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    if (loading) {
//        SwipeRefresh(
//            // Show the loading spinner—`loading` is `true` in this code path
//            state = rememberSwipeRefreshState(true),
//            onRefresh = { /* DO NOTHING */ },
//            content = { },
//        )
//        var expanded by remember { mutableStateOf(false) }
//是否在刷新
        var isRefreshing by remember{ mutableStateOf(true) }
        //下拉刷新的状态管理
        val pullRefreshState = rememberPullRefreshState(
            refreshing = isRefreshing,
            onRefresh = { isRefreshing = true }
        )
        //刷新时的业务处理
        if (isRefreshing) {
//            onRefreshing()
            isRefreshing = false    //刷新业务执行完毕后修改状态
        }
        Box(modifier = modifier
            .fillMaxSize()
            .pullRefresh(state = pullRefreshState)
        ) {
//            content()
            PullRefreshIndicator(
                refreshing = isRefreshing,
                state = pullRefreshState,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }
    } else {
        Column(
            modifier
                .fillMaxWidth()
                .padding(all = dimensionResource(id = R.dimen.horizontal_margin))
                .verticalScroll(rememberScrollState())
        ) {
            val textFieldColors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = Color.Transparent,
                unfocusedBorderColor = Color.Transparent,
                cursorColor = colorScheme.primary
            )
            OutlinedTextField(
                value = title,
                modifier = Modifier.fillMaxWidth(),
                onValueChange = onTitleChanged,
                placeholder = {
                    Text(
                        text = stringResource(id = R.string.title_hint),
                    )
                },
                textStyle = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold),
                maxLines = 1,
                colors = textFieldColors
            )
            OutlinedTextField(
                value = description,
                onValueChange = onDescriptionChanged,
                placeholder = { Text(stringResource(id = R.string.description_hint)) },
                modifier = Modifier
                    .height(350.dp)
                    .fillMaxWidth(),
                colors = textFieldColors
            )
        }
    }
}

